package com.fingard.dsp.bank.directbank.mybank01;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by Ross on 2017-06-06.
 */
public class MYBank01Transaction extends MYBank01Base implements ITransaction {

    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用ant.ebank.trans.record.query
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }

    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = -1;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom < tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int tmpNowPage = 1;
                int tmpTotalPage = 0;
                while (true) {
                    MYBank01Header bankHeader = new MYBank01Header();
                    bankHeader.function = "ant.ebank.trans.record.query";
                    bankHeader.signFields = "queryStartDate,queryEndDate,pageSize,pageIndex,cardNo,bizTypeList,tradeInStatusList,tradeAmtMin,tradeAmtMax";
                    bankHeader.signValueField = "sign";

                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    Date tmpDateNow = new Date();
                    bankHeader.reqMsgID = Format.DateTime17Format.format(tmpDateNow);
                    bankHeader.reqTime = tmpDateNow;

                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeStartElement("body");
                    xmlWriter.writeElementString("partner", bankFront.operator);
                    //tmpCalendarFrom.set(Calendar.DATE, tmpCalendarFrom.get(Calendar.DATE) - 1);
                    xmlWriter.writeElementString("queryStartDate", Format.DateTimeFormat.format(tmpCalendarFrom.getTime()));
                    tmpClndrStepTo.set(Calendar.DATE, tmpClndrStepTo.get(Calendar.DATE) + 1);
                    tmpClndrStepTo.add(Calendar.SECOND, -1);
                    Calendar currentCal = Calendar.getInstance();
                    currentCal.setTime(new Date());
                    if (tmpClndrStepTo.compareTo(currentCal) > 0) {
                        tmpClndrStepTo = currentCal;
                    }
                    xmlWriter.writeElementString("queryEndDate", Format.DateTimeFormat.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("pageSize", "50");
                    xmlWriter.writeElementString("pageIndex", String.valueOf(tmpNowPage));
                    xmlWriter.writeElementString("cardNo", p_req7516.actNum);
                    xmlWriter.writeElementString("bizTypeList", "");
                    xmlWriter.writeElementString("tradeInStatusList", "success");
                    xmlWriter.writeElementString("tradeAmtMin", "-999999999999999");
                    xmlWriter.writeElementString("tradeAmtMax", "999999999999999");
                    xmlWriter.writeElementString("sign", "");
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();

                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
                    XmlTextReader tmpBkReader;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpRetCode = tmpBkReader.getFirstText("/document/response/body/resultInfo/resultStatus");
                            if (tmpRetCode != null && tmpRetCode.equals("S")) {
                                //tmpTotalPage = Integer.parseInt(tmpBkReader.getFirstText("/document/response/body/pageIndex"));
                                // #start "提取各返回节点内容"
                                //if (tmpTotalPage == 0)//记录为空
                                //{
                                //    break;
                                //}
                                while (tmpBkReader.read("/document/response/body/tranHisList")) {
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    XElement tmpRetNode = tmpBkReader.readedXElement;
                                    String tranHisListStr = new String(Base64.decodeBase64(tmpRetNode.innerText), "UTF-8");
                                    WriteBankLogLn("返回的交易明细内容为：" + tranHisListStr);
                                    if (tranHisListStr.length() > 0) {
                                        JSONArray array = JSONArray.fromObject(tranHisListStr);
                                        tmpTotalPage = array.size();
                                        for (int i = 0; i < array.size(); i++) {
                                            JSONObject job = array.getJSONObject(i);

                                            tmpRetDetail.actArea = p_req7516.actArea;
                                            tmpRetDetail.actNum = job.get("ownerCardNo").toString();
                                            tmpRetDetail.recAccBank = job.get("oppositeOrgName") == null ? "" : job.get("oppositeOrgName").toString();
                                            tmpRetDetail.recAccName = job.get("oppositeName") == null ? "" : job.get("oppositeName").toString();
                                            tmpRetDetail.recAccNum = job.get("oppositeCardNo") == null ? "" : job.get("oppositeCardNo").toString();
                                            String tranTimeStr = job.get("tradeExpectEnd") == null || job.get("tradeExpectEnd").toString().length() == 0 ? (job.get("tradeGmtModified") == null || job.get("tradeGmtModified").toString().length() == 0 ? (job.get("tradeGmtCreate") == null || job.get("tradeGmtCreate").toString().length() == 0 ? "" : job.get("tradeGmtCreate").toString()) : job.get("tradeGmtModified").toString()) : job.get("tradeExpectEnd").toString();

                                            if (tranTimeStr.length() > 0) {
                                                Date tranTime = Format.DateTimeFormat.parse(tranTimeStr);
                                                tmpRetDetail.tranDate = Format.Date10Format.format(tranTime);
                                                tmpRetDetail.tranTime = tranTimeStr;
                                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                            }
                                            BigDecimal curUnit = new BigDecimal(100);
                                            BigDecimal tranAmt = new BigDecimal(job.get("tradeAmt").toString());
                                            tranAmt = tranAmt.divide(curUnit).setScale(2, BigDecimal.ROUND_HALF_UP);
                                            String tradeInOutFlag = job.get("tradeInOutFlag").toString();
                                            //交易收支标记 ("0", "收入"), ("1", "支出");
                                            if (tradeInOutFlag.equals("0")) {
                                                if (tranAmt.compareTo(BigDecimal.ZERO) == -1) {
                                                    tmpRetDetail.cdFlag = "1";
                                                } else {
                                                    tmpRetDetail.cdFlag = "2";
                                                }
                                            } else if (tradeInOutFlag.equals("1")) {
                                                if (tranAmt.compareTo(BigDecimal.ZERO) == 1) {
                                                    tmpRetDetail.cdFlag = "2";
                                                } else {
                                                    tmpRetDetail.cdFlag = "1";
                                                }
                                            } else {
                                                tmpRespCode = "-1";
                                                tmpRespInfo = "银行返回收支标识无法识别，请核对！";
                                                break;
                                            }
                                            tmpRetDetail.tranAmt = tranAmt.toString().replace("-", "");

                                            tmpRetDetail.seqId = job.get("bizNo").toString();
                                            String tradeRemark = job.get("tradeRemark").toString();
                                            String tradeName = job.get("tradeName").toString();
                                            tmpRetDetail.comment = tradeName;
                                            tmpRetDetail.usage = tradeRemark;
                                            tmpRetDetail.abstr = pickupAbstr(tradeRemark, tradeName);
                                            tmpRetDetail.originator = job.get("bankOperaterId") == null ? "" : job.get("bankOperaterId").toString();
                                            tmpRetDetail.billNum = job.get("tradeNo").toString();
                                            tmpRetDetail.billType = job.get("bizType").toString();

                                            retAts.writeRetDetail(tmpRetDetail);
                                        }
                                    }
                                }
                                // #end
                            } else {
                                // #start "查询失败"
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpBkReader.getFirstText("/document/response/body/resultInfo/resultMsg");
                                break;
                                // #end
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                    if (tmpTotalPage < 50) {
                        break;
                    }
                    tmpNowPage++;
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.SECOND, 1);
                ;
                //tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }
}
